#!/bin/bash

# MySQL 8 Deployment Script for k3d

set -e  # Exit on any error

echo "=== MySQL 8 Deployment on k3d ==="

# Check if k3d is installed
if ! command -v k3d &> /dev/null; then
    echo "Error: k3d is not installed. Please install k3d first."
    exit 1
fi

# Check if kubectl is installed
if ! command -v kubectl &> /dev/null; then
    echo "Error: kubectl is not installed. Please install kubectl first."
    exit 1
fi

# Check if registry config exists
if [ ! -f "${HOME}/.k3d/k3d-registries.yaml" ]; then
    echo "Warning: Registry config not found at ${HOME}/.k3d/k3d-registries.yaml"
    echo "This may cause issues with pulling images."
fi

# Check if cluster already exists
if k3d cluster list | grep -q mycluster; then
    echo "Cluster 'mycluster' already exists."
    read -p "Do you want to delete and recreate it? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "Deleting existing cluster..."
        k3d cluster delete mycluster
    else
        echo "Using existing cluster."
    fi
fi

# Create cluster if it doesn't exist
if ! k3d cluster list | grep -q mycluster; then
    echo "Creating k3d cluster with registry configuration..."
    k3d cluster create mycluster \
        --port '30006:30006@server:0' \
        --registry-config "${HOME}/.k3d/k3d-registries.yaml" \
        --wait
fi

# Set kubeconfig
echo "Setting kubeconfig context..."

# Write kubeconfig to file and set context
k3d kubeconfig write mycluster > /dev/null 2>&1
export KUBECONFIG=/Users/zhengxin/.k3d/kubeconfig-mycluster.yaml

# Give the cluster a moment to stabilize
sleep 5

# Check if all k3d cluster core services are running
echo "Checking k3d cluster core services status..."

# Function to check pod status with proper label detection
check_pod_running() {
    local label=$1
    local namespace=$2
    local service_name=$3
    
    echo "Checking $service_name..."
    
    # First check if any pods exist with this label
    local pod_count=$(kubectl get pods -l $label -n $namespace --no-headers 2>/dev/null | wc -l | tr -d ' ')
    
    if [ "$pod_count" -eq 0 ]; then
        echo "Warning: No pods found with label $label in namespace $namespace (this may be normal)"
        return 0
    fi
    
    # Wait for pods to be ready
    if kubectl wait --for=condition=ready pod -l $label --timeout=60s -n $namespace >/dev/null 2>&1; then
        # Additional check to ensure pod is actually running
        local status=$(kubectl get pods -l $label -n $namespace -o jsonpath='{.items[0].status.phase}' 2>/dev/null)
        if [ "$status" = "Running" ]; then
            echo "✓ $service_name is Running"
            return 0
        else
            echo "Warning: $service_name status is $status"
            return 0
        fi
    else
        echo "Warning: $service_name is not ready (this may be normal during startup)"
        return 0
    fi
}

# Check core system pods
echo "Checking core system pods..."
# Check nodes
kubectl get nodes --no-headers | awk '{print $1}' | while read node; do
    echo "Checking node: $node"
    if kubectl wait --for=condition=ready node/$node --timeout=30s >/dev/null 2>&1; then
        echo "✓ Node $node is Ready"
    else
        echo "Warning: Node $node is not ready"
    fi
done

# Check if we can access the cluster
echo "Verifying cluster connectivity..."
kubectl cluster-info >/dev/null 2>&1 || {
    echo "Error: Cannot connect to cluster"
    exit 1
}

echo "✓ Cluster is accessible"


# Deploy MySQL
echo "Deploying MySQL with persistent storage..."
kubectl apply -f k3d-pv-pvc.yaml
kubectl apply -f mysql-local-dev.yaml

# Wait for deployment to be ready
echo "Waiting for MySQL pod to be ready..."
kubectl wait --for=condition=ready pod -l app=mysql --timeout=120s

# Show deployment status
echo "=== Deployment Status ==="
echo "Pods:"
kubectl get pods -l app=mysql
echo ""
echo "PV and PVC:"
kubectl get pv,pvc
echo ""
echo "Services:"
kubectl get svc

# Show connection information
echo "=== Connection Information ==="
echo "To connect from within the cluster:"
echo "kubectl exec -it \$(kubectl get pods -l app=mysql -o jsonpath='{.items[0].metadata.name}') -- mysql -u root -prootpassword -e \"SHOW DATABASES;\""
echo ""
echo "To connect from host (if mysql client is installed):"
echo "1. Check port mapping: docker port k3d-mycluster-serverlb"
echo "2. Connect: mysql -h localhost -P 30006 -u root -p (password: rootpassword)"
echo ""
echo "To view data in k3d container:"
echo "docker exec -it k3d-mycluster-server-0 ls -la /tmp/k3d-mysql-data"

echo "=== Deployment Complete ==="